# -*- coding: utf-8 -*-

from google.appengine.ext import db
from dicthash.utils import Bunch
from .models import Note


def NotePaginator(namespace, lenta_id, limit, back=False):
    """ """
    lenta_key = db.Key.from_path('Lenta', lenta_id, namespace=namespace)
    query = Note.all(namespace=namespace).ancestor(lenta_key).filter('isDraft =', False).order('-pubDate')
    
    def get_page_of_notes(dttm=None):
        """ """
        if dttm:
            notes = query.filter('pubDate <' if not back else 'pubDate >', dttm).fetch(limit)
        else:
            notes = query.fetch(limit)
        
        if notes:   
            max_dttm = notes[-1].pubDate if len(notes) == limit else None
            min_dttm = notes[0].pubDate if dttm else None
        else:
            max_dttm = min_dttm = None    
        
        return Bunch(notes=notes, max_dttm=max_dttm, min_dttm=min_dttm)
    
    return get_page_of_notes


def NoteByTagPaginator(namespace, lenta_id, tag_name, limit, back=False):
    """ """
    lenta_key = db.Key.from_path('Lenta', lenta_id, namespace=namespace)
    query = Note.all(namespace=namespace).ancestor(lenta_key). \
                filter('isDraft =', False).filter('tags =', tag_name).order('-pubDate')
    
    def get_page_of_notes(dttm=None):
        """ """
        if dttm:
            notes = query.filter('pubDate <' if not back else 'pubDate >', dttm).fetch(limit)
        else:
            notes = query.fetch(limit)
        
        if notes:   
            max_dttm = notes[-1].pubDate if len(notes) == limit else None
            min_dttm = notes[0].pubDate if dttm else None
        else:
            max_dttm = min_dttm = None    
        
        return Bunch(notes=notes, max_dttm=max_dttm, min_dttm=min_dttm)
    
    return get_page_of_notes
